package org.auf.controllers;

import java.util.Collection;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.auf.core.Controller;
import org.auf.core.FrontController;
import org.auf.model.IPairedDAO;
import org.auf.model.ITestDAO;
import org.auf.model.IUserDAO;
import org.auf.model.Paired;
import org.auf.model.PairedDAOJDBC;
import org.auf.model.Question;
import org.auf.model.Test;
import org.auf.model.TestDAOJDBC;
import org.auf.model.User;
import org.auf.model.UserDAOJDBC;

public class EvaluateTestController extends Controller {
	static Logger log = Logger.getLogger(FrontController.class.getName());

	@Override
	public void show() {
		String idTest, value;
		int i=1, total = 0, correct = 0;
		Question q;
		boolean error=true, cookie=false;
		User actual;
		idTest = (String) request.getAttribute("id");
		Test exam = new Test();
		ITestDAO testdao = new TestDAOJDBC();
		exam = testdao.selectTestById(idTest);
		value = (String) request.getAttribute("answer" + i);
		Collection<Question> questions = exam.getQuestions();
		Iterator<Question> it = questions.iterator();
		if (request.getSession().getAttribute("userTemp")!=null)
			actual = (User) request.getSession().getAttribute("userTemp");
		else
			actual = user;
		while (value!=null && error) {
			if (it.hasNext()) {
				q = (Question) it.next();
				correct = q.getCorrect();
			}
			else {
				log.error("Coleta la ha cagado.");
				error = false;
			}
			if (correct == Integer.valueOf(value))
				total = total++;
			i++;
			value = (String) request.getAttribute("answer" + i);
		}
		if (!error) {
			//DAO: coger voluntario del friki a partir de su ultimo emparejamiento
			Paired pair = new Paired();
			IPairedDAO paireddao = PairedDAOJDBC.getInstance();
			pair = paireddao.selectLastPairedByGeek(actual);
			User volunteer = pair.getVolunteer();
			//DAO: guardar en voluntario: notavoluntarioactual + (notafrikianterior - notafrikiactual)
			IUserDAO userdao = UserDAOJDBC.getInstance();
			int notaAux = actual.getScore()-i;
			volunteer.setScore(volunteer.getScore()+notaAux);
			userdao.updateUserScore(volunteer);
			//DAO: guardar en friki: notafrikiactual
			actual.setScore(i);
			userdao.updateUserScore(actual);
			//DAO: modifico paired para poner el test como hecho
			pair.setTestCompleted(true);
			if (request.getSession().getAttribute("userTemp")!=null) {
				paireddao.insertPaired(pair);
				cookie = true;
			} else {
				paireddao.updatePairedTestCompleted(pair);
				cookie = false;
			}
		view.load("message");
		if (cookie) {
			//view.assignVar("geek", request.getSession().getAttribute("userTemp").getGeek()); //WTF?!?!?!?
		} else {
			view.assignVar("geek", new Boolean(user.getGeek()).toString());
			view.assignVar("text", "Gracias por realizar su test.");
			view.show();
			}
		}
	}
}
